import React from 'react';
import { fetchDepartmentTree } from '../Department/service';

const getTreeData = (data = []) =>
    data.map(item => ({
        ...item,
        value: item.id,
        title: item.departmentName,
        key: item.id,
        children: item.children ? getTreeData(item.children) : []
    }));

const useDepartmentTree = companyId => {
    const [data, setData] = React.useState([]);
    const [loading, setLoading] = React.useState(true);

    const fetchData = async () => {
        setLoading(true);
        const { data: rowData = [], code } = (await fetchDepartmentTree({ companyId })) || {};
        if (code === 10000) {
            const finalData = getTreeData(rowData);
            setData(finalData);
        }
        setLoading(false);
    };

    React.useEffect(() => {
        fetchData();
    }, [companyId]);

    return [loading, data];
};

export default useDepartmentTree;
